import dayjs from 'dayjs'
import {
  queryIndicatorDataByTimeType as _queryIndicatorDataByTimeType,
  updateRealTimeData as _updateRealTimeData,
} from '@/api/modules/indicator'
import { STORAGE_MODES } from '@/enum/modules/indicator'

export function getData(date: Date = new Date(), m: number = 400) {
  const times = Array.from(
    { length: Math.round(24 * 60 / 2) },
    (_, i) => dayjs(date).add(2 * i, 'minute').format('YYYY-MM-DD HH:mm'),
  )

  return [
    ['时间', ...times],
    ['数值', ...times.map(() => +((Math.random() * 40 + m).toFixed(2)))],
  ]
}

/**
 * 实时-近24小时
 * 小时-近24小时
 * 日-近30天
 * 月-近12个
 * 年-近5年
 * @param tt 时间类型
 */
export function getDefaultTimes(tt: STORAGE_MODES) {
  switch (tt) {
    case STORAGE_MODES.NOW:
    case STORAGE_MODES.HOUR:
      return {
        initialStartTime: dayjs().subtract(24, 'hour').format('YYYY-MM-DD HH:mm:ss'),
        initialEndTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
    case STORAGE_MODES.DAY:
      return {
        initialStartTime: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
        initialEndTime: dayjs().format('YYYY-MM-DD'),
      }
    case STORAGE_MODES.MONTH:
      return {
        initialStartTime: dayjs().subtract(12, 'month').format('YYYY-MM'),
        initialEndTime: dayjs().format('YYYY-MM'),
      }
    case STORAGE_MODES.YEAR:
      return {
        initialStartTime: dayjs().subtract(5, 'year').format('YYYY'),
        initialEndTime: dayjs().format('YYYY'),
      }
  }
}

export function useIndicatorDataCurve() {
  const [loading, setLoading] = useState(false)
  const data = shallowRef<any>([])
  const indicator = shallowRef({
    indicatorName: '',
    indicatorNumber: '',
    unit: '',
    indicatorCode: '',
  })

  async function queryIndicatorDataByTimeType(params: {
    indicatorNumber: string
    timeType: STORAGE_MODES
    startTime: string
    endTime: string
  }) {
    setLoading(true)
    try {
      const { data: res } = await (_queryIndicatorDataByTimeType)(params)
      indicator.value = {
        indicatorName: res.indicatorName,
        indicatorNumber: res.indicatorNumber,
        unit: res.unit,
        indicatorCode: res.indicatorCode,
      }
      data.value = [
        ['时间', ...res.lineChartVo.xaxis?.data ?? []],
        [`${res.indicatorName}(${res.unit})`, ...res.lineChartVo.series[0]?.data ?? []],
      ]
    }
    catch (e) {
      console.warn(e)
    }
    finally {
      setLoading(false)
    }
  }

  async function updateRealTimeData(params: {
    indicatorCode: string
    value: number
    time: string
  }) {
    await _updateRealTimeData(params)
  }

  return {
    loading,
    data,
    indicator,
    queryIndicatorDataByTimeType,
    updateRealTimeData,
  }
}
